const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const { User, RegCode } = require('../db')
const securityUtil = require('../util/security')
const mailUtil = require('../util/mail')
const emailInterceptor = require('../intercepror/email')
const userC = require('../controller/user')
const fs = require('fs')
const log4js = require('../config/log4js')
const log = log4js.getLogger()

const route = new Router({
  prefix: '/auth'
})

route
  .post('/login', async ctx => {
    const { username, password, email } = ctx.request.body
    const user = await User.findOne({
      $or: [
        { username },
        { email }
      ]
    })
    log.info(`user is \n${user}`)
    if (!user || securityUtil.encryptPassword(password) !== user.password) {
      ctx.throw('用户不存在或密码错误')
    } else {
      const token = jwt.sign({
        username: user.username,
        password: user.password,
        id: user._id
      }, securityUtil.getSecret(user.password), {
        expiresIn: '30d'
      })
      ctx.body = {
        ...user._doc,
        token
      }
    }
  })

  .post('/regist', async ctx => {
    const { username, password, email, regCode } = ctx.request.body
    const RC = await RegCode.findById(regCode)
    if (RC) {
      if (RC.expireTime < Date.now()) {
        ctx.throw('注册码已过期')
      }
    } else {
      ctx.throw('注册码不存在')
    }
    await RC.updateOne({
      useTime: Date.now()
    })
    const user = new User({
      username,
      email,
      regCode: RC._id,
      avatar: ctx.request.files && ctx.request.files.avatar ? fs.readFileSync(ctx.request.files.avatar.path) : null,
      password: securityUtil.encryptPassword(password)
    })
    await user.save()
    ctx.body = '注册成功!'
  })

  .get('/email/code', emailInterceptor.generateEmailToken,
    async ctx => {
      const { email, code, token, username, genTime } = ctx.tl
      mailUtil.sendMail({
        to: email,
        subject: `email code for dear ${username}`,
        text: `your email code is ${code} which is valid for 5 minutes`
      })

      ctx.body = {
        token,
        genTime
      }
    })

  .get('/email', async ctx => {
    const user = await User.findOne({
      email: ctx.request.body.email
    })
    if (user) {
      ctx.throw('email exists')
    } else {
      ctx.body = {}
    }
  })

  .get('/username', async ctx => {
    const user = await User.findOne({
      username: ctx.request.body.username
    })
    if (user) {
      ctx.throw('username exists')
    } else {
      ctx.body = {}
    }
  })

  .post('/password', emailInterceptor.verifyEmailToken, userC.updatePassword)

module.exports = route
